let tdtToken = 'db07d88f894c5e78200cc0e0fefbf3e6';

class SceneUtil {

  /**
   * tdtImageLayerAdd() 天地图影像图层和注记加载
   * @static
   * @param {*} viewer
   * @memberof SceneUtil
   */
  static tdtImageLayerAdd(viewer) {
    viewer.imageryLayers.addImageryProvider(new Cesium.TiandituImageryProvider({
      token: tdtToken
    }));

    let imageryLayers = viewer.imageryLayers;
    //初始化天地图全球中文注记服务，并添加至影像图层
    let labelImagery = new Cesium.TiandituImageryProvider({
      mapStyle: Cesium.TiandituMapsStyle.CIA_C, //天地图全球中文注记服务（经纬度投影）
      token: tdtToken
    });
    imageryLayers.addImageryProvider(labelImagery);
    return imageryLayers;
  }

  static sceneLayerAdd(viewer, url, name, layerType,index) {
    let imageryLayer = undefined;
    switch (layerType) {
      case "layer_sm_map":
        imageryLayer = this.superMap2D_MapSerivceLayerAdd(viewer, url,index);
        break;
      case "layer_sm_scene":
        imageryLayer = this.sceneServiceLayerAdd(viewer, url);
        break;
      case "layer_sm_s3m":
        imageryLayer = this.s3mLayerAdd(viewer, url, name,index);
        break;
      case "layer_tdt_img":
        imageryLayer = this.tdtImageLayerAdd(viewer);
    }
    return imageryLayer;
  }

  static sceneLayerRemove(viewer, imageryLayer, layerType) {
    switch (layerType) {
      case "layer_sm_map":
        this.superMap2D_MapServiceLayerRemove(viewer, imageryLayer);
        break;
      case "layer_sm_scene":
        this.sceneServiceLayerRemove(viewer, imageryLayer);
        break;
      case "layer_sm_s3m":
        this.s3mLayerRemove(viewer, imageryLayer);
        break;
    }
  }

  static sceneLayerPosition(viewer, imageryLayer, layerType, url) {
    switch (layerType) {
      case "layer_sm_map":
        this.superMap2D_MapServiceLayerPosition(viewer, imageryLayer, url);
        break;
      case "layer_sm_scene":
        this.sceneServiceLayerPosition(viewer, imageryLayer);
        break;
      case "layer_sm_s3m":
        this.s3mLayerPosition(viewer, imageryLayer);
        break;
    }
  }

  /**
   * terrainLayerAdd() 添加地形图层
   * @static
   * @param {*} viewer
   * @param {*} terrainUrl
   * @memberof SceneUtil
   */
  static terrainLayerAdd(viewer, terrainUrl) {
    // let terrainProvider = new Cesium.CesiumTerrainProvider({
    //     url : terrainUrl,
    //     isSct : true//地形服务源自SuperMap iServer发布时需设置isSct为true
    // }),
    // viewer.terrainProvider = terrainProvider;
  }

  /**
   * 超图2D图层加载
   * @param viewer
   * @param url
   * @param index
   * @returns {*}
   */
  static superMap2D_MapSerivceLayerAdd(viewer, url,index) {
    //利用服务url创建SuperMapImageryProvider实例
    let mapServiceProvider = new Cesium.SuperMapImageryProvider({
      url: url //地图服务
    });
    let imageryLayers = viewer.imageryLayers;
    let imageryLayer = undefined;
    if(index){
       imageryLayer = imageryLayers.addImageryProvider(mapServiceProvider,index);
    }else{
       imageryLayer = imageryLayers.addImageryProvider(mapServiceProvider);
    }
    return imageryLayer;
  }

  /**
   * 超图2D图层移除
   * @param viewer
   * @param imageryLayer
   * @returns {*}
   */
  static superMap2D_MapServiceLayerRemove(viewer, imageryLayer) {
    let succeed = viewer.imageryLayers.remove(imageryLayer, true);
    return succeed;
  }

  /**
   * 添加S3M图层
   * @param viewer
   * @param url
   * @param name
   * @param index
   * @returns {*}
   */
  static s3mLayerAdd(viewer, url, name,index) {
    let scene = viewer.scene;
    //添加S3M图层服务
    let promise = undefined;
    if(index){
      promise = scene.addS3MTilesLayerByScp(url, {name: name},index);
    }else {
      promise = scene.addS3MTilesLayerByScp(url, {name: name});
    }
    Cesium.when(promise, layers => {
    });
    return promise;
  }

  /**
   * 打开场景图层
   * @param viewer
   * @param sceneUrl
   * @returns {*|void|IDBOpenDBRequest|Promise<Cache>|Document|Window}
   */
  static sceneServiceLayerAdd(viewer, sceneUrl) {
    let scene = viewer.scene;
    let promise = scene.open(sceneUrl);
    return promise;
  }

  /**
   * 移除场景图层
   * @param viewer
   * @param promise
   */
  static sceneServiceLayerRemove(viewer, promise) {
    let scene = viewer.scene;
    Cesium.when(promise, layers => {
      layers.forEach(layer => {
        scene.layers.remove(layer.name, true);
      });
    });
  }

  /**
   * 移除S3M图层
   * @param viewer
   * @param promise
   */
  static s3mLayerRemove(viewer, promise) {
    let scene = viewer.scene;
    Cesium.when(promise, layer => {
      scene.layers.remove(layer.name, true);
    })
  }

  static superMap2D_MapServiceLayerPosition(viewer, imageryLayer, url) {
    let getMapStatusService = new SuperMap.MapService(url, {
      serverType: SuperMap.ServerType.ISERVER,
      eventListeners: {
        processCompleted: (serviceResult) => {
          let rectangle = Cesium.Rectangle.fromDegrees(serviceResult.result.bounds.left, serviceResult.result.bounds.bottom, serviceResult.result.bounds.right, serviceResult.result.bounds.top);
          viewer.camera.flyTo({
            destination: rectangle,
            duration: 5
          });

        }
      },
    });
    getMapStatusService.processAsync();
  }

  static s3mLayerPosition(viewer, promise) {
    Cesium.when(promise, layer => {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(layer.lon, layer.lat, layer.height + 200),
        duration: 5
      });
    })
  }

  static sceneServiceLayerPosition(viewer, promise) {
    Cesium.when(promise, layers => {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(layers[0].lon, layers[0].lat, layers[0].height + 200),
        duration: 5
      });
    })
  }

  /**
   * 解析图层url
   * @param url
   * @private
   */
  static parseLayerUrl(url) {
    if (url) {
      this.parseLayerUrlParam(url);
      const urlArray = url.split('?');
      const realUrl = url.replace(urlArray[urlArray.length - 1], '');
      return realUrl.substring(0, realUrl.length - 1);
    }
    return url
  }

  /**
   * 解析图层url参数
   * @param url
   * @private
   */
  static parseLayerUrlParam(url) {
    if (url) {
      const urlArray = url.split('?');
      try {
        var obj = JSON.parse(
          '{"' +
          decodeURIComponent(urlArray[urlArray.length - 1])
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
          '"}'
        )
      } catch (e) {
        console.warn("图层URL参数配置不正确，不能正常解析的JSON");
        return {};
      }
      return obj;

    }

  }



}

export {SceneUtil};
